
<template>
  <!-- 项目部管理岗位人员配置表 -->
  <a-form-model ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="editModel == 0 ? {} : rules">
    <a-spin :spinning="loading">
      <!-- 表单 -->
      <a-card>
        <title-name title="项目部管理岗位人员配置表"></title-name>

        <a-button
          :disabled="editModel == 0"
          type="primary"
          class="mb12"
          icon="plus"
          @click="
            visible = true
            initData.type = 1
          "
        >
          新增部门
        </a-button>
        <a-button
          :disabled="editModel == 0"
          type="primary"
          class="mb12 ml12"
          icon="plus"
          @click="
            visible = true
            initData.type = 2
          "
        >
          新增岗位
        </a-button>
        <s-table bordered ref="table" size="default" rowKey="key" :columns="columns" :data="loadData" :alert="true" show-size-changer show-quick-jumper :showPagination="false">
          <template slot="action" slot-scope="text, record, index">
            <a-popconfirm title="确定要删除?" @confirm="() => delItem(index)">
              <a v-if="editModel != 0 && record.isDeleted != 1">删除</a>
            </a-popconfirm>
          </template>
          <template v-for="col in ['authorizer', 'staffingId', 'mainDuty']" :slot="col" slot-scope="text, record">
            <div :key="col">
              <ASelectOrgPeople v-if="col === 'staffingId'" :disabled="editModel == 0" isBlur mode="multiple" :init="false" :form="baseFormInfo" key-value="projectOrgId"  v-model="record[col]"></ASelectOrgPeople>
              <BaseInput v-else v-model="record[col]" :disabled="editModel == 0" :maxLength="col == 'authorizer' ? 30 : 300" />
            </div>
          </template>
        </s-table>
        <div class="mt12">
          注：1）EPC及类EPC项目应设置设计部、计划部，宜设置招采部，并配置专职部门经理及相关人员。<br />
          2）EPC及类EPC以外项目应设置专（兼）职计划经理（工程师）、设计经理（工程师），专（兼）职计划经理（工程师）需归项目经理直管。
        </div>
      </a-card>
    </a-spin>
    <DialogForm
      ref="dialogForm"
      :visible.sync="visible"
      :edit-model="'2'"
      :form="initData"
      :header-title="initData.type == 1 ? '增加部门' : '增加岗位'"
      :width="800"
      :height="1100"
      :isEmit="false"
      :rules="rulesDialog"
      :form-list="formListDialog"
      @confirm="submitForm"
      :clearForm="true"
      :styles="{ width: '550px' }"
    />
  </a-form-model>
</template>
<script>
import { api } from '@/api/projectManagementPlanning/jobPersionTable'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import BSelect from '@/components/BComponents/BSelect'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import DialogForm from '@/components/DialogForm' // 弹窗

export default {
  name: 'projectAuthorizationLetter',
  extends: new BaseEditPage(),
  components: {
    SelectProject,
    BSelect,
    SelectSubCompany,
    ASelectOrgPeople,
    DialogForm
  },
  props: {
    baseFormInfo: {
      // 是否作为审批详情
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      loading: false, // 加载控件
      visible: false, //人员选择控件
      editModel: 1, // 操作状态:0 查看;1 编辑
      form: { data: [] }, // 表单
      id: '',
      initData: { department: undefined, positionName: '', type: -1 },
      loadingBtn: {
        DELETE: false,
        DRAFT: false,
        SUBMITTED: false,
        REJECTED: false
      },
      loadData: () => {
        return new Promise((resolve, reject) => {
          resolve({
            data: this.form.data || []
          })
        })
      },
      update: api.updateList,
      rules: {}, // 校验规则
      rulesDialog: {
        department: [{ required: true, message: '请输入' }],
        department1: [{ required: true, message: '请选择' }],
        positionName: [{ required: true, message: '请输入' }]
      },
      init: false, // 初始化控件
      selectDepartment: []
    }
  },
  watch: {},
  computed: {
    formListDialog() {
      return [
        // 手写普通选择框
        {
          type: 'a-select',
          keyName: 'department1',
          label: '部门名称',
          hidden: this.initData.type == 1,

          span: 24,
          replaceFields: {
            value: 'department', // 默认为value
            label: 'department' // 默认为label
          },
          data: this.selectDepartment
        },
        {
          keyName: 'department',
          type: 'BaseInput',
          hidden: this.initData.type == 2,
          span: 24,
          label: '部门名称'
        },
        {
          keyName: 'positionName',
          type: 'BaseInput',
          span: 24,
          label: '岗位名称'
        }
      ]
    },
    columns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          customRender(text, record, index) {
            return index + 1
          }
        },
        {
          title: '部门',
          dataIndex: 'department',
          width: '10%',
          customRender: (text, row, index) => {
            let obj = {
              children: text,
              attrs: {}
            }
            let lastIndex = -1
            let firstIndex = this.form.data.findIndex((v) => v.department === text)
            this.form.data.map((m, i) => {
              if (m.department == text) {
                lastIndex = i
              }
            })
            if (index === 0) {
              obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
            } else {
              // 若该行考核内容和上一行一致，则使其隐藏
              if (this.form.data[index - 1].department === text) {
                obj.attrs.rowSpan = 0
                // 若不是，则往下合并与改行内容一致行的总行数
              } else {
                obj.attrs.rowSpan = lastIndex === firstIndex ? 1 : lastIndex + 1 - firstIndex
              }
            }

            return obj
          }
        },
        {
          title: '岗位名称',
          dataIndex: 'positionName'
        },
        {
          title: '人员配置',
          dataIndex: 'authorizer',
          width: '25%',
          scopedSlots: { customRender: 'authorizer' }
        },
        {
          title: '人员姓名',
          dataIndex: 'staffingId',
          width: '15%',
          scopedSlots: { customRender: 'staffingId' }
        },

        {
          title: '主要职责',
          dataIndex: 'mainDuty',
          scopedSlots: { customRender: 'mainDuty' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: '5%',
          scopedSlots: { customRender: 'action' }
        }
      ]
    }
  },
  created() {},
  mounted() {
    // 不为添加时请求详情
    this.getDetailData()
  },

  methods: {
    submitForm(data) {
      data.department = data.department || data.department1
      let index = 0
      let item = {
        department: data.department,
        positionName: data.positionName,
        authorizer: '',
        staffingId: [],
        mainDuty: ''
      }
      if (this.initData.type == 1) {
        this.form.data.push(item)
        this.initSelectDepartment()
      } else {
        this.form.data.forEach((e, i) => {
          if (data.department == e.department) {
            index = i
          }
        })

        this.form.data.splice(index + 1, 0, item)
      }

      this.visible = false
      this.$refs.table.refresh()
    },
    initSelectDepartment() {
      this.selectDepartment = []
      this.form.data?.forEach((e, i) => {
        if (i == 0) {
          this.selectDepartment.push(e)
        }
        if (i > 0 && e.department != this.form.data[i - 1].department) {
          this.selectDepartment.push(e)
        }
      })
    },
    getDetailData() {
      this.loading = true
      api
        .getDetails({ id: this.id, version: this.$route.query.version || void 0 })
        .then((res) => {
          this.form = res
          this.form.data?.forEach((e, i) => {
            e.staffingId = e.staffingId?.split(',') || []
          })
          this.initSelectDepartment()

          this.$refs.table.refresh()
          let that = this
          setTimeout(function () {
            that.loading = false
          }, 2000)
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    delItem(index) {
      this.form.data.splice(index, 1)
      this.$refs.table.refresh()
    },
    jobPersionTableSaveDrafts() {
      this.handleSubmit(0)
    },
    jobPersionTableSubmit() {
      // if (this.validateForm()) {
      this.handleSubmit(1)
      // }
    },

    /**
     * 提交表单
     */
    handleSubmit(status) {
      let form = this.$clone(this.form)

      if (form.data.length == 0) {
        form.data.push({ mainId: this.id })
      }
      form.data[0].status = status
      form.data.forEach((e) => {
        e.staffingId = e.staffingId?.join(',')
      })
      if (status == 1) {
        this.handleSecondSub(form.data)
        return
      }
      this.loading = true
      api
        .updateList(form.data)
        .then(() => {
          this.loading = false
          this.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
          this.$multiTab.close()
        })
        .catch(() => {
          this.loading = false
          this.$message.warning(err.data.message)
        })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .form-item  {
  .ant-input:not([disabled]),
  .ant-select:not(.ant-select-disabled) .ant-select-selection,
  .ant-calendar-picker-input,
  .ant-input-number:not([disabled]),
  .ant-cascader-picker {
    border-color: #e4ac0b;
    background-color: #fff9e8;
  }
  .ant-input-disabled,
  .ant-input-number-disabled .ant-input-number-input,
  .ant-time-picker-input[disabled] {
    border-color: #d9d9d9 !important;
    background-color: #f5f5f5 !important;
  }
  .remark {
    .ant-input {
      border-color: inherit;
      background-color: initial;
    }
  }
}
</style>